Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve type guards for type variables #15576

Merged
merged 5 commits into from
May 7, 2017
Merged

Conversation

ahejlsberg
Copy link
Member

With this PR, when a node is the left hand expression of a property access, element access, or call expression, and the type of the node includes type variables with constraints that are nullable, we fetch the apparent type of the node before performing control flow analysis such that narrowings apply to the constraint type. For example:

type Item = {
    (): string;
    x: string;
}

function f1<T extends Item | undefined>(obj: T) {
    if (obj) {
        obj.x;     // Ok
        obj["x"];  // Ok
        obj();     // Ok
    }
}

Prior to this PR, the property access, element access, and call expressions above were errors.

Fixes #14091.
Fixes #14415.

@@ -11708,6 +11710,29 @@ namespace ts {
return annotationIncludesUndefined ? getTypeWithFacts(declaredType, TypeFacts.NEUndefined) : declaredType;
}

function isApparentTypePosition(node: Node) {
const parent = node.parent;
return parent.kind === SyntaxKind.PropertyAccessExpression ||
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

&& (<PropertyAccessExpression >parent).expression === node; ?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No need to. This function is only ever called on the left hand side of a property access expression (the right hand side is just an identifier and not actually an expression).

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants